package com.zxj.common.core.utils;

import com.zxj.common.core.contains.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Map;

public class JwtUtils {

    /**
     * 生成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从令牌中获取数据
     *
     * @param token  令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    /**
     * 获取用户身份
     * @param claims
     * @return
     */
    public static String getUserKey(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_KEY));
    }

    /**
     * 获取用户ID
     * @param claims
     * @return
     */
    public static String getUserId(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_ID));
    }

    private static String toStr(Object value) {
        if (value == null) {
            return "";
        }
        return value.toString();
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEsInVzZXJLZXkiOiI3ZWZkZTJiYi0wOTcxLTQxNTQtOGJmNi0wMGMyMGJjNzkyZTcifQ.KT7zuhEBt4ZuRyeRwNjsCFWSGIN2V2FZ_mox1azcDbnFZnzioW8Fb09t3jB-w-uLIz0_L77QOUt_uurp38leNw";
        Claims claim = parseToken(token, "tianwanggaidihu@123");
        System.out.println(claim);
    }
}
